<template>
	<!-- 客服中心 -->
	<view class="contenter">
		<view style="height: 1000rpx;" v-if="UserId.length==0" class="flex flex-column justify-center align-center">
			<text class="text-muted">暂时没人给您发消息哦</text>
			<image src="@/static/icon/comment-times.png" mode=""></image>
		</view>
		<view v-else class="flex chat">
			<view class="flex flex-column a" style="height: 1200rpx; overflow-y: scroll;">
				<view @click="handle(i)" v-for="(item,i) in UserId" :key="item.UserId"
					class="flex justify-between align-center p-4 px-8" style="border: 2rpx solid #eee;"
					:class="item.isShow?'text-white bg-'+ThemeColors:''">
					<image style="width: 100rpx;" src="../../../static/icon/1.png" mode="widthFix"></image>
					<view class="" style="width: 60%;">
						<view class="font-weight-bold text-ellipsis">{{item.Nick!=''?item.Nick:item.UserId}}</view>
						<view :title="item.Enterprise_Name" class="font-small text-ellipsis"
							v-if="item.Authentication=='1'">{{item.Enterprise_Name}}</view>
						<view class="font-small">
							{{item.Authentication==''?'未认证':item.Authentication=='1'?'企业商户':'个体商户'}}
						</view>
					</view>
					<view class="bg-danger text-white text-center"
						style="border-radius: 50%;width: 40rpx;height: 40rpx;line-height: 40rpx;">
						{{item.msgList.length}}
					</view>
				</view>
			</view>
			<!-- 右 -->
			<view v-if="item.isShow" v-for="(item,i) in UserId" :key="item.UserId"
				class="bg-light flex-1 flex flex-column " id="scrollview" style="height: 1200rpx;">
				<!-- 聊天消息区 -->
				<scroll-view :scroll-top="scrollTop" :scroll-with-animation="true" :scroll-y="true" id="msglistview"
					class=" bg-light scroll-view a" style="height: 90%;border: 2rpx solid #eee;overflow-y: scroll;w">
					<view class="chat-body">
						<!-- 聊天记录 -->
						<view v-for="(item_,index) in item.msgList" :key="index">
							<!-- 自己发的消息 -->
							<view class="item self" v-if="item_.userContent != ''">
								<!-- 文字内容 -->
								<view class="content right">
									{{item_.userContent}}
								</view>
								<!-- 头像 -->
								<view class="flex flex-column align-center">
									<text class="font-small">{{item_.time}}</text>
									<image mode="widthFix" style="width: 70rpx;" class="avatar"
										src="../../../static/icon/1.png">
									</image>
								</view>
							</view>
							<!-- 机器人发的消息 -->
							<view class="item Ai" v-if="item_.botContent != ''">
								<!-- 头像 -->
								<view class="flex flex-column align-center">
									<image mode="widthFix" style="width: 70rpx;" class="avatar"
										src="../../../static/icon/1.png">
									</image>
								</view>
								<!-- 文字内容 -->
								<view class="flex flex-column align-center ml-3">
									<text class="font-small">{{item_.time}}</text>
									<view class="content left">
										{{item_.botContent}}
									</view>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
				<!-- 发送消息区 -->
				<view class="p-4">
					<view class="flex justify-between w-100">
						<view class="send-msg a" style="width: 80%; height: 100rpx; overflow-y: scroll;">
							<textarea style="width: 100%;" v-model="item.chatMsg" maxlength="300" confirm-type="send"
								@confirm="handleSend(i)" placeholder="快来聊天吧~" :show-confirm-bar="false"
								:adjust-position="false" @focus.stop="focus" @blur.stop="blur" auto-height></textarea>
						</view>
						<view class="flex-1">
							<button @click.stop="handleSend(i,item)" style="height: 100%;background-color: burlywood;"
								class="flex justify-center align-center" type="default">发送</button>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import times from '@/static/js/utils.js'
	import {
		Message
	} from 'element-ui'
	const app = getApp()
	import {
		GroupServesHistory
	} from '@/api/group.js'
	import {
		GoodsFileAdd
	} from '@/api/global.js'
	export default {
		name: "customer",
		data() {
			return {
				scrollTop: 0,
				ThemeColors: app.globalData.ThemeColors,
				Domain_IMG: app.globalData.Domain_IMG,
				UserId: [],
				msgList: [],
				is_open_socket: false, // 确保websocket是打开状态
				hearBeatInterval: null, //心跳
			};
		},
		mounted() {
			this.connectSocketInit()
			let data = {
				Group_ID: uni.getStorageSync('loginInfo').enterprise,
				User_Type: 'service',
				Enterprise_Info_SerialNumber: uni.getStorageSync('loginInfo').enterprise,
			}
			this.getHistoryList(data)
		},
		beforeDestroy() {
			console.log(2)
			this.closeSocket()
		},
		methods: {
			//获取消息历史记录
			async getHistoryList(data) {
				const res = await GroupServesHistory({
					data,
				})
				if (res.redirect && res.redirect == 'REDIRECT') {
					console.log(res.redirect);
				} else if (res.Status == 'success') {
					console.log(res);
					this.UserId = res.Data
				}
			},
			//发送的消息添加到消息记录
			async MessagesFileAdd(data) {
				const res = await GoodsFileAdd({
					data,
				})
				if (res.redirect && res.redirect == 'REDIRECT') {
					console.log(res.redirect);
				} else if (res.Status == 'success') {
					console.log(res);
				}
			},
			closeSocket() {
				if(this.is_open_socket){
					this.socketTask.close()
					clearInterval(this.hearBeatInterval)
				}
			},
			//websocket连接
			connectSocketInit() {
				// 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
				this.socketTask = uni.connectSocket({
					url: app.globalData.Domain_Socket + "/websocket?userId=Group" + uni.getStorageSync('loginInfo').enterprise,
					success(data) {
						console.log("websocket连接成功");
					},
				});
				// // 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
				this.socketTask.onOpen((res) => {
					console.log("WebSocket连接正常打开中...！");
					this.is_open_socket = true;
					// 注：只有连接正常打开中 ，才能正常成功发送消息
					this.hearBeatInterval = setInterval(() => {
						this.socketTask.send({
							data: 'ping',
						});
					}, 5000)
					// 注：只有连接正常打开中 ，才能正常收到消息
					this.socketTask.onMessage((res) => {
						console.log(JSON.parse(res.data))
						let message = JSON.parse(res.data).data.message
						let time = JSON.parse(res.data).data.time
						let UserId = JSON.parse(res.data).userId.replace('Group', '')

						if (this.isArrNull(UserId, this.UserId)) {
							if (this.UserId.length == 0) {
								this.UserId.push({
									UserId,
									Nick: '',
									Enterprise_Name: '',
									Authentication: '',
									chatMsg: '',
									isShow: true,
									msgList: []
								})
							} else {
								this.UserId.push({
									UserId,
									Nick: '',
									Enterprise_Name: '',
									Authentication: '',
									chatMsg: '',
									isShow: false,
									msgList: []
								})
							}
							this.getMember(UserId)
						}
						this.UserId.forEach(item => {
							if (item.UserId == UserId) {
								item.msgList.push({
									botContent: message,
									userContent: "",
									time
								})
							}
						})
					});
				})
				// // 这里仅是事件监听【如果socket关闭了会执行】
				this.socketTask.onClose(() => {
					this.is_open_socket = false;
					clearInterval(this.hearBeatInterval)
					console.log("已经被关闭了")
				})
			},
			focus() {
				console.log('进入输入框')
				this.ScrollBottom()
			},
			blur() {
				console.log('点击')
				this.ScrollBottom()
			},
			handle(i) {
				this.UserId.forEach(item => {
					item.isShow = false
				})
				this.UserId[i].isShow = true
			},
			handleSend(i, item) {
				if (item.chatMsg.trim() == '') {
					Message({
						message: '不可以发送空消息',
						type: 'warning'
					})
					return
				}
				const this_ = this
				//如果消息不为空
				if (!this.UserId[i].chatMsg || !/^\s+$/.test(this.UserId[i].chatMsg)) {
					this.UserId[i].msgList.push({
						botContent: "",
						userContent: this.UserId[i].chatMsg,
						time: times.nowtime()
					});
					console.log(this_.UserId[i].msgList.length)
					this_.ScrollBottom(this_.UserId[i].msgList.length)
					if (this.is_open_socket && this.UserId[i].chatMsg != "") {
						this.socketTask.send({
							data: JSON.stringify({
								time: times.nowtime(),
								message: this.UserId[i].chatMsg,
								userId: this.UserId[i].UserId,
							}),
							async success() {
								console.log("消息发送成功");
							},
						});
						let data = {
							Data: JSON.stringify({
								group_serves_news: [{
									Group_Serves_SerialNumber: '',
									Group_User_Number: this.UserId[i].UserId,
									Group_Serves_ID: uni.getStorageSync('loginInfo').enterprise,
									Group_Message: this.UserId[i].chatMsg,
									Group_Message_Time: times.nowtime(),
									Group_Message_Type: '',
									Enterprise_Info_SerialNumber: uni.getStorageSync('loginInfo').enterprise,
									Row_Status: '1'
								}]
							}),
						}
						this.MessagesFileAdd(data)
					}
					this.UserId[i].chatMsg = ''
				}
			},
			ScrollBottom(i=0) {
				console.log('滚动了')
				// this.scrollTop = (124-48)*i
				this.$nextTick(()=>{
					this.scrollTop = 10000 + i*10
				})
			}
		}
	};
</script>

<style lang="scss">
	.contenter {
		width: 100%;
		padding: 30rpx;

		background-color: #fff;

		.el-form {
			display: flex;
			flex-wrap: wrap;
		}

	}

	$chatContentbgc: #C2DCFF;
	$sendBtnbgc: #4F7DF5;

	.chat {
		.topTabbar {
			width: 100%;
			height: 90rpx;
			line-height: 90rpx;
			display: flex;
			margin-top: 80rpx;
			justify-content: space-between;

			.icon {
				margin-left: 20rpx;
			}

			.text {
				margin: auto;
				font-size: 16px;
				font-weight: 700;
			}

			.button {
				width: 10%;
				margin: auto 20rpx auto 0rpx;
			}
		}

		.scroll-view {
			::-webkit-scrollbar {
				display: none;
				width: 0 !important;
				height: 0 !important;
				-webkit-appearance: none;
				background: transparent;
				color: transparent;
			}

			// background-color: orange;
			background-color: #F6F6F6;

			.chat-body {
				display: flex;
				flex-direction: column;
				padding-top: 23rpx;

				// background-color:skyblue;
				.self {
					justify-content: flex-end;
				}

				.item {
					display: flex;
					padding: 23rpx 30rpx;
					// background-color: greenyellow;

					.right {
						background-color: $chatContentbgc;
					}

					.left {
						background-color: #FFFFFF;
					}

					// 聊天消息的三角形
					.right::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						left: 100%;
						top: 10px;
						border: 12rpx solid transparent;
						border-left: 12rpx solid $chatContentbgc;
					}

					.left::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						top: 10px;
						right: 100%;
						border: 12rpx solid transparent;
						border-right: 12rpx solid #FFFFFF;
					}

					.content {
						text-align: center;
						position: relative;
						max-width: 486rpx;
						border-radius: 8rpx;
						word-wrap: break-word;
						padding: 24rpx 24rpx;
						margin: 0 24rpx;
						border-radius: 5px;
						font-size: 32rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #333333;
						line-height: 42rpx;
					}

					.avatar {
						display: flex;
						justify-content: center;
						width: 78rpx;
						height: 78rpx;
						border-radius: 50rpx;
						overflow: hidden;

						image {
							align-self: center;
						}

					}
				}
			}
		}

		/* 底部聊天发送栏 */
		.chat-bottom {
			width: 100%;
			height: 100rpx;
			background: #F4F5F7;
			transition: all 0.1s ease;

			.send-msg {
				display: flex;
				align-items: flex-end;
				padding: 16rpx 30rpx;
				width: 100%;
				min-height: 177rpx;
				position: fixed;
				bottom: 0;
				background: #fff;
				transition: all 0.1s ease;
			}

			.uni-textarea {
				padding-bottom: 70rpx;

				textarea {
					width: 537rpx;
					min-height: 75rpx;
					max-height: 500rpx;
					background: #f1f1f1;
					border-radius: 40rpx;
					font-size: 32rpx;
					font-family: PingFang SC;
					color: #333333;
					line-height: 74rpx;
					padding: 5rpx 8rpx;
					text-indent: 30rpx;
				}
			}

			.send-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 76rpx;
				margin-left: 25rpx;
				width: 120rpx;
				height: 75rpx;
				background: #ed5a65;
				border-radius: 50rpx;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #FFFFFF;
				line-height: 28rpx;
			}
		}
	}

	.a::-webkit-scrollbar {
		display: none;
	}
</style>